package com.osmino.contacts.history;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ToggleButton;
import com.osmino.contacts.R;
import com.osmino.contacts.entity.Call;
import com.osmino.contacts.entity.Contact;
import com.osmino.contacts.help.HelpActivity;
import com.osmino.contacts.provider.CallLogQueries;
import com.osmino.contacts.provider.ContactsContractQueries;
import com.osmino.contacts.settings.SettingsActivity;
import com.osmino.core.AbsListActivity;
import com.osmino.core.DialogGenerator;
import com.osmino.core.DialogInfo;
import com.osmino.core.TextPickerDialog;

public final class HistoryActivity extends AbsListActivity implements IHistoryController {

	//	private CallLogAdapter mAdapter;
	//	private CallLogProviderProxy mCallLogProvider;
	private CallLogCursorAdapter mAdapter;
	private DialogGenerator mDialogGenerator;
	private static final int[] sButtonIds = new int[] { R.id.history_all_button, R.id.history_incoming_button,
			R.id.history_missed_button, R.id.history_outgoing_button };
	private static final int DEFAULT_TOGGLED_INDEX = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDialogGenerator = new DialogGenerator(this, this);
		//mCallLogProvider = new CallLogProviderProxy(this);
		setContentView(R.layout.history_view);
		int buttonArrayLength = sButtonIds.length;
		for (int i = 0; i < buttonArrayLength; i++) {
			ToggleButton button = (ToggleButton) findViewById(sButtonIds[i]);
			button.setOnClickListener(this);
		}
		ToggleButton button = (ToggleButton) findViewById(sButtonIds[DEFAULT_TOGGLED_INDEX]);
		button.setChecked(true);
		//		List<CallInfo> listCallInfo = mCallLogProvider.getAllCalls();
		//		mAdapter = new CallLogAdapter(this, this, listCallInfo);
		//		setListAdapter(mAdapter);
		Cursor cursor = CallLogQueries.getAllCalls(this);
		startManagingCursor(cursor);
		mAdapter = new CallLogCursorAdapter(this, cursor);
		setListAdapter(mAdapter);
		getListView().setOnItemClickListener(this);
		registerForContextMenu(getListView());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mAdapter = null;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
			case R.id.dialog_edit_before_call:
				dialog = mDialogGenerator.createEditBeforeCallDialog();
				break;
			case R.id.dialog_quick_message:
				dialog = mDialogGenerator.createQuickMessageDialog(null, null);
				break;
			default:
				dialog = super.onCreateDialog(id);
		}
		return dialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
			case R.id.dialog_edit_before_call:
				mDialogGenerator.prepareEditBeforeCallDialog((TextPickerDialog) dialog);
				break;
			case R.id.dialog_quick_message:
				mDialogGenerator.prepareQuickMessageDialog((AlertDialog) dialog);
				break;
		}
	}

	@Override
	public void onDialogCallback(DialogInfo dialogCallbackInfo) {
		int dialogId = dialogCallbackInfo.dialogId;
		if (dialogId == R.id.dialog_edit_before_call) {
			onEditBeforeCallDialogCallback(dialogCallbackInfo);
		}
	}

	private void onEditBeforeCallDialogCallback(DialogInfo dialogCallbackInfo) {
		int whichButton = dialogCallbackInfo.whichButton;
		String text = dialogCallbackInfo.text;
		if (whichButton == Dialog.BUTTON_POSITIVE) {
			Uri callUri = Uri.parse("tel:" + text);
			Intent callIntent = new Intent(Intent.ACTION_CALL, callUri);
			startActivity(callIntent);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.recents_option_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		switch (itemId) {
			case R.id.recents_option_clear:
				CallLogQueries.deleteCallHistory(this);
				break;
			case R.id.recents_option_settings:
				Intent settingsCall = new Intent(this, SettingsActivity.class);
				startActivity(settingsCall);
				break;
			case R.id.recent_options_help:
				Intent helpCall = new Intent(this, HelpActivity.class);
				startActivity(helpCall);
				break;
		}
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		getMenuInflater().inflate(R.menu.recents_context_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		switch (itemId) {
			case R.id.contact_option_call:
				onCallOption(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);
				break;
			case R.id.contact_option_edit_before_call:
				onEditBeforeCallOption((AdapterView.AdapterContextMenuInfo) item.getMenuInfo());
				break;
			case R.id.contact_option_send_SMS:
				onSendSmsOption((AdapterView.AdapterContextMenuInfo) item.getMenuInfo());
				break;
			case R.id.contact_option_clear_from_callog:
				onClearCallFromLogOption((AdapterView.AdapterContextMenuInfo) item.getMenuInfo());
				break;
			case R.id.contact_option_view_contact:
				onViewContactOption((AdapterView.AdapterContextMenuInfo) item.getMenuInfo());
				break;
			case R.id.contact_option_send_contact_by_SMS:
				onSendContactBySmsOption((AdapterView.AdapterContextMenuInfo) item.getMenuInfo());
				break;
		}
		return false;
	}

	@Override
	public void onClick(View view) {
		int viewId = view.getId();
		for (int i = 0; i < sButtonIds.length; i++) {
			ToggleButton button = (ToggleButton) findViewById(sButtonIds[i]);
			button.setChecked(false);
		}
		stopManagingCursor(mAdapter.getCursor());
		Cursor cursor = null;
		switch (viewId) {
			case R.id.history_all_button:
				cursor = CallLogQueries.getAllCalls(this);
				break;
			case R.id.history_incoming_button:
				cursor = CallLogQueries.getIncomingCalls(this);
				break;
			case R.id.history_outgoing_button:
				cursor = CallLogQueries.getOutgoingCalls(this);
				break;
			case R.id.history_missed_button:
				cursor = CallLogQueries.getMissedCalls(this);
				break;
		}
		startManagingCursor(cursor);
		mAdapter.changeCursor(cursor);
		ToggleButton button = (ToggleButton) findViewById(viewId);
		button.setChecked(true);
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		int viewId = adapterView.getId();
		if (viewId == getListView().getId()) {
			onCallOption(position);
		}
	}

	private void onCallOption(int position) {
		Call itemInfo = mAdapter.getItem(position);
		Uri callUri = Uri.parse("tel:" + itemInfo.number);
		Intent callIntent = new Intent(Intent.ACTION_CALL, callUri);
		startActivity(callIntent);
	}

	private void onEditBeforeCallOption(AdapterView.AdapterContextMenuInfo menuInfo) {
		Call itemInfo = mAdapter.getItem(menuInfo.position);
		mDialogGenerator.setDialogText(R.id.dialog_edit_before_call, itemInfo.number);
		showDialog(R.id.dialog_edit_before_call);
	}

	private void onSendSmsOption(AdapterView.AdapterContextMenuInfo menuInfo) {

	}

	private void onClearCallFromLogOption(AdapterView.AdapterContextMenuInfo menuInfo) {
		CallLogQueries.deleteCall(this, menuInfo.id);
	}

	private void onViewContactOption(AdapterView.AdapterContextMenuInfo menuInfo) {
		Call itemInfo = mAdapter.getItem(menuInfo.position);
		Contact contact = null;
		Cursor cursor = ContactsContractQueries.getContactsByPhoneLookup(this, itemInfo.number);
		cursor.moveToFirst();
		if (cursor.getCount() > 0) {
			contact = new Contact(this, cursor, Contact.MASK_ONLY_MAIN);
		}
		cursor.close();
		if (contact == null) {
			mDialogGenerator.setDialogTitle(R.id.dialog_quick_message, getString(R.string.recent));
			mDialogGenerator.setDialogText(R.id.dialog_quick_message, getString(R.string.no_contacts_found));
			showDialog(R.id.dialog_quick_message);
		} else {
			String lookup = contact.lookupKey;
			long id = contact.id;
			Uri.Builder uriBuilder = ContactsContract.Contacts.CONTENT_LOOKUP_URI.buildUpon();
			Uri uri = ContentUris.appendId(uriBuilder.appendPath(lookup), id).build();
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		}
	}

	private void onSendContactBySmsOption(AdapterView.AdapterContextMenuInfo menuInfo) {

	}
}
